#ifndef SINGLE_MODEL_H
#define SINGLE_MODEL_H

#include <atomic>
#include <mutex>
#include <memory>
#include <iostream>
#include <string>


//带模板的通用单例类
template <typename T>
class SafeDeletor_T
{
public:
    void operator()(T *st)
    {
        delete st;
    }
};

template <typename T>
class Single_T
{
protected:
    Single_T() = default;
    Single_T(const Single_T<T> &st) = delete;
    Single_T &operator=(const Single_T<T> &st) = delete;
    ~Single_T(){}

public:
    static std::shared_ptr<T> GetInst()
    {
        if (single != nullptr) {
            return single;
        }

        s_mutex.lock();
        if (single != nullptr) {
            s_mutex.unlock();
            return single;
        }

        //额外指定删除器
        single = std::shared_ptr<T>(new T, SafeDeletor_T<T>());
        //也可以指定删除函数
        // single = std::shared_ptr<SingleAutoSafe>(new SingleAutoSafe, SafeDelFunc);
        s_mutex.unlock();
        return single;
    }

private:
    static std::shared_ptr<T> single;
    static std::mutex s_mutex;
};

//模板类的static成员要放在h文件里初始化
template <typename T>
std::shared_ptr<T> Single_T<T>::single = nullptr;
//
template <typename T>
std::mutex Single_T<T>::s_mutex;
//
#endif // SINGLE_MODEL_H
